﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace AF_WinformTool
{
    public class RunInThread
    {
        private Action _delegate;
        private Thread _Thread;
        private Action _Callback;
        private System.Windows.Forms.Control _ControlHost;
        public RunInThread()
        {
            _Thread = new Thread(doWork);
        }

        private void doWork()
        {
            if (_delegate != null)
            {
                _delegate();
            }
            if (_Callback != null)
            {
                if (_ControlHost != null)
                {
                    if (!_ControlHost.IsDisposed && _ControlHost.IsHandleCreated)
                    {
                        _ControlHost.BeginInvoke(_Callback);
                    }
                }
                else
                {
                    _Callback();
                }
            }
        }

        /// <summary>
        /// 在线程中运行指定代码 
        /// <example>RunInThread.Run(this, (Action)delegate(){});</example>
        /// </summary>        
        /// <param name="host"></param>
        /// <param name="doSomething"></param>
        /// <param name="callback"></param>                
        public static void Run(System.Windows.Forms.Control host, Action doSomething, Action callback = null)
        {
            RunInThread _RunInThread = new RunInThread();
            _RunInThread._ControlHost = host;
            _RunInThread._delegate = doSomething;
            _RunInThread._Callback = callback;
            _RunInThread._Thread.Start();
        }
    }
}
